import React, { useState } from 'react';
import { useRequest } from 'ice';

import { Card, Form, Table, Input, Select, DatePicker, Button, TableColumnType, Modal } from 'antd';

/* ---------------- API ------------------ */

// 分页查询
async function searchPage(params: any): Promise<{ list: any[]; total: number }> {
  console.log(params);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        list: new Array(10).fill(0).map((_, index) => ({
          key: index,
          name: '胡彦斌',
          age: 32,
          address: '西湖区湖底公园1号',
        })),
        total: 100,
      });
    }, 1000);
  });
}

/* ---------------- Modal ------------------ */

// 查看视图（查看详情）
const useViewModal = () => {
  const [item, setItem] = useState(undefined);

  const openModal = (lookItem?: any) => {
    setItem(lookItem);
  };

  return {
    openModal,
    modal: (
      <Modal open={!!item} title="查看数据" footer={null} onCancel={() => setItem(undefined)}>
        {JSON.stringify(item)}
      </Modal>
    ),
  };
};

/* ---------------- MAIN ------------------ */

// 标准表单
function StanderTable() {
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [filters, setFilters] = useState({});

  const { data, loading } = useRequest(
    () =>
      searchPage({
        pageIndex: current,
        pageSize,
        filters,
      }),
    {
      manual: false,
      refreshDeps: [current, pageSize, filters],
    },
  );
  const { list = [], total = 0 } = data || {};

  /* --- form相关的 --- */

  const [tableForm] = Form.useForm();

  const onReset = () => {
    tableForm.resetFields();
    onSearch();
  };

  const onSearch = () => {
    setCurrent(1);
    setFilters(tableForm.getFieldsValue());
  };

  /* --- table相关的 --- */

  const columns: Array<TableColumnType<any>> = [
    {
      title: 'RowHead',
      dataIndex: 'key',
      align: 'center',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
    },
    {
      title: '住址',
      dataIndex: 'address',
    },
    {
      title: '操作',
      align: 'center',
      render: (item) => (
        <>
          <Button type="link" onClick={() => openModal(item)}>
            查看
          </Button>
          <Button type="link" danger>
            删除
          </Button>
        </>
      ),
    },
  ];

  const onPageChange = (newPageIndex: number, newPageSize: number) => {
    setCurrent(newPageIndex);
    setPageSize(newPageSize);
  };

  /* --- 一些 Modal --- */
  const { openModal, modal: ViewModal } = useViewModal();

  return (
    <div className="h-full space-y-10px p-10px flex flex-col">
      <Card title="筛选条件">
        <Form form={tableForm} className="w-full" layout="inline" onSubmitCapture={onSearch}>
          <Form.Item label="名称" name="name">
            <Input />
          </Form.Item>
          <Form.Item label="类型" name="type">
            <Select
              style={{ width: '182px' }}
              options={[
                { label: '选项一', value: '1' },
                { label: '选项二', value: '2' },
                { label: '选项三', value: '3' },
              ]}
            />
          </Form.Item>
          <Form.Item label="创建时间" name="createTime">
            <DatePicker.RangePicker />
          </Form.Item>
          <div className="flex-1 text-right space-x-10px">
            <Button htmlType="submit" type="primary">
              查询
            </Button>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
          </div>
        </Form>
      </Card>
      <Card title="列表" className="flex-1 flex-card" bodyStyle={{ paddingBottom: 0 }}>
        <Table
          className="flex-table"
          loading={loading}
          columns={columns}
          dataSource={list}
          pagination={{ total, current, pageSize, onChange: onPageChange }}
        />
      </Card>

      {/* 一些模态对话框 */}
      {ViewModal}
    </div>
  );
}

export default StanderTable;
